import { useStore } from '@/hooks';
import { Button, Dialog, Form, DatePicker } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import { FieldsGrid } from '@/pages/company/CompanyInfo/stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import moment from 'moment';

const FromItem = Form.Item;

const formItemLayout = {
  style: { marginTop: 10 },
};

const Index = ({ onCancel, modal, onSubmit, ...formProps }) => {
  const { companyStore: store } = useStore();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [data] = useState(() => observable({}));

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      const company = await store.get(global.me.accountId);
      const { stopTakingOrders } = company;
      const { stopFrom, stopTo } = stopTakingOrders || {};
      editCtx.origin = _.cloneDeep(data);
      _.assign(data, company);
      _.set(data, 'orderTime', [stopFrom ? moment(stopFrom).add('8', 'hours') : null, stopTo ? moment(stopTo).add('8', 'hours') : null]);
    })();
  }, []);

  if (!data) return <></>;

  const overrideModel = {
    orderTime: {
      ui: {
        renderer: (v) => (<DatePicker.RangePicker
          style={{ width: '100%' }}
          value={v}
          format="YYYY-MM-DD"
          disabledDate={disabledDate}
        />),
        itemProps: {
        },
        span: 1,
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(data, name, value);
    if (name === 'stopTakingOrders.stopOrder') {
      _.set(data, 'orderTime', []);
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const disabledDate = (current) => {
    // 如果当前日期大于等于今天，返回 false（不禁用）
    // 如果当前日期小于今天，返回 true（禁用）
    return current && current < moment().subtract(1, 'day').endOf('day');
  };

  /**
   * @description 提交表单实现修改用户
   * @param {*} r formData
   */
  const handleSubmit = async (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    onSubmit?.(data);
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={false}
      {...formProps}
      value={data}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={data}
        columns={1}
        mode={'view'}
        fields={(['name', 'tel'])}
      />
      <FieldsGrid
        formData={data}
        columns={1}
        mode={''}
        itemLayout={{ ...formItemLayout }}
        overrideModel={overrideModel}
        fields={(['stopTakingOrders.stopOrder', 'orderTime'])}
      />
      <FromItem style={{ marginTop: 100 }}>
        <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
        <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
      </FromItem>
    </Form>
  );
};

export default observer(Index);
